
package com.viweb.storemanager.ui.database;

public class ProcessTask {

    private int lengthOfTask;
    private int current = 0;
    private boolean done = false;
    private boolean canceled = false;

    public ProcessTask(int lengthOfTask) {
        this.lengthOfTask = lengthOfTask;
    }

    /**
     * Called from ProgressBarDemo to start the task.
     */
    public void go() {
        final SwingWorker worker = new SwingWorker() {

            public Object construct() {
                current = 0;
                done = false;
                canceled = false;
                return new ActualProcessTask();
            }
        };
        worker.start();
    }

    /**
     * Called from ProgressBarDemo to find out how much work needs
     * to be done.
     */
    public int getLengthOfTask() {
        return lengthOfTask;
    }

    /**
     * Called from ProgressBarDemo to find out how much has been done.
     */
    public int getCurrent() {
        return current;
    }

    public void stop() {
        canceled = true;
    }

    /**
     * Called from ProgressBarDemo to find out if the task has completed.
     */
    public boolean isDone() {
        return done;
    }

    /**
     * The actual long running task.  This runs in a SwingWorker thread.
     */
    class ActualProcessTask {

        ActualProcessTask() {
            //Fake a long task,
            //making a random amount of progress every second.
            while (!canceled && !done) {
                try {
                    Thread.sleep(1000); //sleep for a second
                    current += Math.random() * 100; //make some progress
                    if (current >= lengthOfTask) {
                        done = true;
                        current = lengthOfTask;
                    }
                } catch (InterruptedException e) {
                    System.out.println("ActualTask interrupted");
                }
            }
        }
    }
}
